package org.budo.mybatis.dao.statement.builder.creator;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.Column;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;

import org.apache.ibatis.session.Configuration;
import org.budo.mybatis.dao.entity.configer.MyBatisDaoEntityConfiger;
import org.budo.mybatis.dao.statement.builder.impl.DefaultStatementBuilder;
import org.budo.support.lang.util.ReflectUtil;
import org.budo.support.lang.util.StringUtil;

/**
 * @author lmw
 */
public abstract class AbstractUpdateStatementCreator extends AbstractStatementCreator {
    public AbstractUpdateStatementCreator(Configuration configuration, DefaultStatementBuilder statementBuilder) {
        super(configuration, statementBuilder);
    }

    protected List<String> updateSetSqls(MyBatisDaoEntityConfiger entityConfiger, Class<?> entityType, Boolean ignoreNull) {
        List<Field> fields = ReflectUtil.getAllFields(entityType);

        List<String> setSqls = new ArrayList<String>();

        for (Field field : fields) {
            Column column = field.getAnnotation(Column.class);
            if (null != column && column.updatable()) {
                String columnName = this.getStatementBuilder().getEntityConfiger().getColumnName(field);

                if (ignoreNull) {
                    setSqls.add("<if test=\"" + field.getName() + " != null\"> " + columnName + " = #{" + field.getName() + "}, </if>");
                } else {
                    setSqls.add(columnName + "=#{" + field.getName() + "}");
                }

                continue;
            }

            if (null != field.getAnnotation(OneToOne.class)//
                    || null != field.getAnnotation(ManyToOne.class)) {
                String joinColumnName = this.getStatementBuilder().getEntityConfiger().getJoinColumnName(field);

                if (StringUtil.isEmpty(joinColumnName)) {
                    continue;
                }

                String idFieldName = entityConfiger.getIdFieldName(field.getType());

                if (ignoreNull) {
                    setSqls.add("<if test=\"" + field.getName() + "!=null and " + field.getName() + "." + idFieldName + " != null\"> " + joinColumnName + " = #{" + field.getName() + "." + idFieldName + "}, </if>");
                } else {
                    setSqls.add(joinColumnName + "=#{" + field.getName() + "." + idFieldName + "}");
                }

                continue;
            }
        }
        return setSqls;
    }
}
